from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from starlette.staticfiles import StaticFiles

from app.api import gateway
from app.utils.database import DatabasePool
from app.message_service.message_sender import MessageSender
from app.message_service.message_receiver import MessageReceiver
from app.message_service.message_processor import MessageProcessor
from app.utils.kafka import KafkaProducer
from app.config import config

import uvicorn
import asyncio

app = FastAPI()

# 添加跨域支持
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)

# 挂载静态文件目录
app.mount("/static", StaticFiles(directory=config.STATIC_DIR), name="static")

# 注册路由模块
app.include_router(gateway.router)


@app.on_event("startup")
async def startup():
    # 初始化数据库连接池
    await DatabasePool.create_pool("static/teacher_data.db")

    # 启动 Kafka Producer 并存入 app.state（全局唯一）
    kafka_producer = KafkaProducer()
    await kafka_producer.start()
    app.state.kafka_producer = kafka_producer

    # 初始化 MessageReceiver 并注入 kafka_producer
    message_receiver = MessageReceiver()
    await message_receiver.start()
    app.state.message_receiver = message_receiver

    # 启动处理器
    processor = MessageProcessor()
    app.state.processor = processor
    asyncio.create_task(processor.start())

    # 启动 Kafka 消费任务（异步常驻）
    message_sender = MessageSender()
    asyncio.create_task(message_sender.start())


@app.on_event("shutdown")
async def shutdown():
    await DatabasePool.close_pool()

    # 关闭 Kafka Producer
    if hasattr(app.state, "kafka_producer"):
        await app.state.kafka_producer.stop()


if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8080)
